package com.min.nio.rpc.client;

import com.min.nio.api.HelloWorld;
import com.min.nio.module.Student;
import com.min.nio.rpc.util.MessageUtils;
import lombok.NonNull;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * create by sirmin on 2018/3/19
 */
public class Client {

   public Object transform(@NonNull Class<?> clazz, @NonNull Method method, Object object) throws Exception{
       final SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost",8888));
       final ByteArrayOutputStream out = new ByteArrayOutputStream();
       final ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
       objectOutputStream.writeObject(object);
       final byte[] objBytes = out.toByteArray();
       final byte[] classNameBytes = clazz.getName().getBytes();
       final byte[] methodNameBytes = method.getName().getBytes();
       byte cl = (byte) classNameBytes.length;
       byte ml = (byte) methodNameBytes.length;
       final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(objBytes.length + cl + ml + 2);
       byteBuffer.put(cl);
       byteBuffer.put(classNameBytes);
       byteBuffer.put(ml);
       byteBuffer.put(methodNameBytes);
       byteBuffer.put(objBytes);
       byteBuffer.flip();
       channel.write(byteBuffer);
       channel.shutdownOutput();
       return MessageUtils.getMessage(channel);
   }


    public static void main(String[] args) throws Exception {
        final Method sayHello = HelloWorld.class.getDeclaredMethod("sayHello", Student.class);
        final Object transform = new Client().transform(HelloWorld.class, sayHello,
                Student.builder()
                        .name("小明")
                        .studentId("1111")
                        .build());
        System.out.println(transform);
    }

}
